# -*- coding: utf8-*-

from WorkRecord import WorkRecord
from Utils import Utils
import Config
import logging
from datetime import datetime,timedelta


logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',level=1)




class Member:
    def __init__(self,name,workRecords):
        self.name = name
        self.workRecords = workRecords
        self.myworkDates = {}

    def worktimeOftheDay(self,date):
        return Utils.formatTime(date+" "+Config.WORKING_TIME)

    def getLateForWorkDays(self):
        '''get the days that be late for work'''


        lateDays = dict()

        for record in self.workRecords:

            #2016-07-01 09：50:50
            startTime = record.startTimeWithDate

            # 2016-07-01 10：00:00
            workTime = self.worktimeOftheDay(record.workDate)

            # 2016-07-01
            workDate = record.workDate

            if  self.isLateToday(record):

                #lateMinutes = str(round((startTime - workTime).seconds/float(60),1))
                lateMinutes = str((startTime - workTime).seconds/60)
                lateseconds = (startTime - workTime).seconds
                isWorkForTripleThanLate = "否"
                if record.hasEndTime():
                    endTime = record.endTimeWithDate
                    isWorkForTripleThanLate = "是" if ((
                                                      endTime - workTime).seconds - 9 * 60 * 60) >=  lateseconds else "否"

                lateDays[workDate] = [lateMinutes,isWorkForTripleThanLate]
        if len(lateDays)>0:
            logging.info("all late days for %s are %s"%(self.name,lateDays.keys()))
        return lateDays

    def isLateToday(self, workRecord):

        return workRecord.hasStartTime() and (workRecord.startTimeWithDate - self.worktimeOftheDay(workRecord.workDate)).seconds <=30*60 and (workRecord.startTimeWithDate - self.worktimeOftheDay(workRecord.workDate)).seconds >0


    def getOOFDay(self, allworkdays):
        '''get all days that out of work'''
        self.getAllRecordDate()

        results = []


        for days in allworkdays:

            # 在所有的工作日列表中有的但是在我的打卡记录中没有的日期判定为缺勤
            if days not in self.myworkDates.keys():

                results.append(days)
        logging.info("all oof days for %s are %s" % (self.name, results))
        return results

    def getWorkOvertime(self,allworkdays):
        '''get all days working over time'''

        results = {}
        for days in self.myworkDates.keys():
            #在我的打卡记录中有的但是在所有的工作日列表中没有的判定为加班
            if days not in allworkdays:
                results[days] = self.myworkDates[days]

        logging.info("all work over time days for %s are %s" % (self.name, results))
        return results


    def getAllRecordDate(self):
        '''get all days that have swiping record'''
        #获取所有的打卡记录，返回为字典，key时打卡日期，value是工作时长，只有一次打卡记录的不统计时长
        for record in self.workRecords:

            m_date = Utils.formatDate(record.workDate)
            if record.hasStartTime() and record.hasEndTime():

                starttime = record.startTimeWithDate
                endtime = record.endTimeWithDate

                self.myworkDates[m_date] = str(
                    round((endtime - starttime - timedelta(hours=1)).seconds / float(3600), 2)) + "(小时)"
            elif not record.hasStartTime():
                self.myworkDates[m_date] = record.endTime + u"(只有下班打卡了)"
            elif not record.hasEndTime():
                self.myworkDates[m_date] = record.startTime + u"(只有上班打卡了)"

                # 统计早退情况

    def getLeaveEarly(self):
            earlyDays = {}
            for record in self.workRecords:
                # 有下班打卡记录
                if record.hasEndTime() and record.hasStartTime():
                    startTime = record.startTimeWithDate

                    endTime = record.endTimeWithDate

                    workTime = record.workDate + " " + Config.OFF_TIME
                    workTime = Utils.formatTime(workTime)
                    workStartTime = record.workDate+ " " + Config.WORKING_TIME
                    workStartTime = Utils.formatTime(workStartTime)


                    if (endTime - startTime).seconds >= 8.5 * 60 * 60 and startTime < workStartTime + timedelta(
                            minutes=30):
                        # 早于6点下班为早退，提前半个小时为早退，超过半个小时算请假
                        if endTime < workTime and (workTime - endTime).seconds <= 0.5 * 60 * 60:
                            earlyDays[record.workDate] = str(round((workTime - endTime).seconds / float(60), 1))
                        # 工作时间>8.5小于9小时为早退
                        elif (endTime - startTime).seconds < 9 * 60 * 60:
                            earlyDays[record.workDate] = str(
                                round((9 * 60 * 60 - (endTime - startTime).seconds) / float(60), 1))
            logging.info("all leave early days for %s are %s" % (self.name, earlyDays.keys()))
            return earlyDays

    def getDailyOverWork(self):
        dailyOverWorkdDays = []
        for record in self.workRecords:
            if record.hasEndTime():
                recordDate = datetime.strptime(record.workDate, "%Y/%m/%d").date()
                endTime = record.endTimeWithDate
                #endTime = Utils.formatTime(endTime)

                if recordDate.weekday() in (0, 1, 2, 3):
                    lateTime = record.workDate + " " + Config.OVERWORK_TIME

                    lateTime = Utils.formatTime(lateTime)
                    if (endTime > lateTime):
                        dailyOverWorkdDays.append(record.workDate)

                elif recordDate.weekday() == 4:

                    lateTime = record.workDate + " " + Config.OVERWORK_TIME_FRIDAY
                    lateTime = Utils.formatTime(lateTime)
                    if (endTime > lateTime):
                        dailyOverWorkdDays.append(record.workDate)
        Utils.formatList(dailyOverWorkdDays)
        logging.info("all daily over work days for %s are %s" % (self.name, dailyOverWorkdDays))
        return dailyOverWorkdDays

        # 统计打卡异常，当天只有一次刷卡记录

    def getSwiptingExcetpion(self):
        exceptionDays = []
        for record in self.workRecords:
            if not record.hasEndTime() or not record.hasStartTime():
                exceptionDays.append(record)
        logging.info("all swipe exception days for %s are %s" % (self.name, exceptionDays))
        return exceptionDays

        # 统计请假情况，有上下班打卡记录但是每天工作时间不满足8小时判定有请假情况

    def getAskforLeave(self):
        askForLeaveDays = {}
        for record in self.workRecords:
            if record.hasEndTime() and record.hasStartTime():
                startTime = record.startTimeWithDate

                endTime = record.endTimeWithDate

                workTime = record.workDate + " " + Config.WORKING_TIME
                workTime = Utils.formatTime(workTime)
                offTime = record.workDate + " " + Config.OFF_TIME
                offTime = Utils.formatTime(offTime)
                if (endTime - startTime).seconds < 8 * 60 * 60 or startTime > workTime + timedelta(
                        minutes=30) or endTime < offTime - timedelta(minutes=30):
                    # 请半天假，下午请假，上午工作满四个小时
                    if endTime <= Utils.formatTime(record.workDate+ " " + "13:00:00") and (
                        endTime - startTime).seconds >= 4 * 60 * 60:
                        askForLeaveDays[record.workDate] = "下午半天"
                    elif startTime >= Utils.formatTime(record.workDate + " " + "14:00:00") and (
                        endTime - startTime).seconds >= 4 * 60 * 60:
                        askForLeaveDays[record.workDate] = "上午半天"

                    elif endTime < offTime - timedelta(minutes=30):
                        # 九点之前到的
                        if (startTime < workTime - timedelta(hours=1)):
                            askForLeaveDays[record.workDate] = str(workTime + timedelta(hours=8) - endTime)
                        # 九点以后10点半之前到的
                        elif startTime >= workTime - timedelta(hours=1) and (
                            startTime <= workTime + timedelta(minutes=30)):
                            askForLeaveDays[record.workDate] = str(startTime + timedelta(hours=9) - endTime)
                        # 10点半以后到的，到的晚走的早的
                        elif startTime < workTime + timedelta(hours=3):
                            askForLeaveDays[record.workDate] = str(
                                startTime - workTime + offTime - endTime + timedelta(hours=1))
                        else:
                            askForLeaveDays[record.workDate] = str(
                                startTime - workTime + offTime - endTime)
                    elif startTime > workTime + timedelta(minutes=30):
                        # 7点之后走的
                        if (endTime > offTime + timedelta(hours=1)):
                            askForLeaveDays[record.workDate] = str(startTime - (offTime - timedelta(hours=8)))
                        # 5点半之后7点之前走的
                        elif (endTime >= offTime - timedelta(minutes=30) and (endTime < offTime + timedelta(hours=1))):
                            askForLeaveDays[record.workDate] = str(startTime - (endTime - timedelta(hours=9)))
                        # 5点半之前走的
                        elif endTime > workTime + timedelta(hours=3):
                            askForLeaveDays[record.workDate] = str(
                                startTime - workTime + offTime - endTime + timedelta(hours=1))
                        else:
                            askForLeaveDays[record.workDate] = str(
                                startTime - workTime + offTime - endTime)
                            # askForLeaveDays[record[0]] = str(endTime-timedelta(hours=9)-startTime)
        logging.info("all ask for leave days for %s are %s" % (self.name, askForLeaveDays.keys()))
        return askForLeaveDays
if __name__ == '__main__':
    workRecords = list()
    workRecordList = [("2016/08/01","","21:01:00"),("2016/08/02","8:31:00","20:33:00"),("2016/08/03","10:29:00",""),
                           ("2016/08/04","10:01:00","18:33:00"),("2016/08/05","10:03:00","20:03:00")]
    for record in workRecordList:
        workRecord = WorkRecord(record[0],record[1],record[2])
        workRecords.append(workRecord)

    member = Member("王晓翠",workRecords)
